package com.example.bledemo.util;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * Created by Peter_Z.
 * <p>
 * Date: 2025/8/4 0004
 */
public class UuidGenerator {
    private static final Random random = new Random();

    public static class WechatUuidData {
        public String id1, id2, id3;
        public String checksum;
        public String uuid;
        public String userData1, userData2;
        public List<String> serviceUuids;
        public String tagId;
        public int tagValue;

        public WechatUuidData(String id1, String id2, String id3, String checksum,
                              String uuid, String userData1, String userData2,
                              List<String> serviceUuids, String tagId, int tagValue) {
            this.id1 = id1;
            this.id2 = id2;
            this.id3 = id3;
            this.checksum = checksum;
            this.uuid = uuid;
            this.userData1 = userData1;
            this.userData2 = userData2;
            this.serviceUuids = serviceUuids;
            this.tagId = tagId;
            this.tagValue = tagValue;
        }
    }

    /**
     * 生成微信小程序风格的UUID数据
     * @param currentStatus 当前状态 (0: 静止, 1: 运动, 2: 行车)
     * @return WechatUuidData对象
     */
    public static WechatUuidData generateWechatUuids(int currentStatus) {
        // 1. 生成标签ID (与微信小程序完全一致)
//        String id1 = generateHexId(2);
        String id1 = "22";
//        String id2 = generateHexId(2);
        String id2 = "33";
//        String id3 = generateHexId(2);
        String id3 ="44";

        // 2. 计算校验和 (与微信小程序完全一致)
        String checksum;
        String uuid;
        if (currentStatus == 0) {
//            checksum = calculateChecksum("1B", "03", "00", "02", id1, id2, id3);
            checksum = calculateChecksum("1B", "03", "00", "01", id1, id2, id3);
//            uuid = "0200";
            uuid = "0100";
        } else {
            checksum = calculateChecksum("1B", "03", "00", "12", id1, id2, id3);
            uuid = "1200";
        }

        // 3. 生成用户数据 (与微信小程序完全一致)
        String userData1 = id2 + id1;
        String userData2 = checksum + id3;

        // 4. 生成标签ID和数值 (与微信小程序完全一致)
        String tagId = "000000" + id1 + id2 + id3;
        int tagValue = Integer.parseInt(id1 + id2 + id3, 16);

        // 5. 构建服务UUID数组 (与微信小程序完全一致)
        List<String> serviceUuids = Arrays.asList(
                uuid,           // 状态相关UUID
                userData1,      // 标签ID部分
                userData2,      // 校验和+标签ID
                "bd50", "b184", "9f32", "9d14", "6fdd", "10d3", "380f", "2d72", "5ea8", "58c2"  // CTE固定数据
        );

        return new WechatUuidData(id1, id2, id3, checksum, uuid, userData1, userData2,
                serviceUuids, tagId, tagValue);
    }

    /**
     * 生成指定长度的十六进制字符串 (与微信小程序hexRandom函数完全一致)
     */
    private static String generateHexId(int length) {
        String hexValues = "0123456789abcdef";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++) {
            result.append(hexValues.charAt(random.nextInt(hexValues.length())));
        }
        return result.toString();
    }

    /**
     * 计算校验和 (与微信小程序checksumFunc函数完全一致)
     */
    private static String calculateChecksum(String hex1, String hex2, String hex3,
                                            String hex4, String hex5, String hex6, String hex7) {
        // 将十六进制字符串转换为十进制数字
        int dec1 = Integer.parseInt(hex1, 16);
        int dec2 = Integer.parseInt(hex2, 16);
        int dec3 = Integer.parseInt(hex3, 16);
        int dec4 = Integer.parseInt(hex4, 16);
        int dec5 = Integer.parseInt(hex5, 16);
        int dec6 = Integer.parseInt(hex6, 16);
        int dec7 = Integer.parseInt(hex7, 16);

        // 进行加法运算
        int result = dec1 + dec2 + dec3 + dec4 + dec5 + dec6 + dec7;

        // 将结果转换回十六进制字符串，取最后2位
        String hexResult = Integer.toHexString(result);
        if (hexResult.length() > 2) {
            hexResult = hexResult.substring(hexResult.length() - 2);
        }

        return hexResult;
    }

    /**
     * 将服务UUID数组转换为字节数组 (模拟微信框架的压缩)
     */
    public static byte[] serviceUuidsToBytes(List<String> serviceUuids) {
        ByteBuffer buffer = ByteBuffer.allocate(serviceUuids.size() * 2);
        for (String uuid : serviceUuids) {
            // 将4位十六进制字符串转换为2字节
            int uuidValue = Integer.parseInt(uuid, 16);
            buffer.putShort((short) uuidValue);
        }
        return buffer.array();
    }

    /**
     * 打印UUID数据详情
     */
    public static void printUuidDetails(WechatUuidData data) {
        System.out.println("=== UUID生成结果 ===");
        System.out.println("标签ID: " + data.tagId);
        System.out.println("标签数值: " + data.tagValue);
        System.out.println("ID1: " + data.id1);
        System.out.println("ID2: " + data.id2);
        System.out.println("ID3: " + data.id3);
        System.out.println("校验和: " + data.checksum);
        System.out.println("状态UUID: " + data.uuid);
        System.out.println("用户数据1: " + data.userData1);
        System.out.println("用户数据2: " + data.userData2);
        System.out.println();
        System.out.println("服务UUID数组:");
        for (int i = 0; i < data.serviceUuids.size(); i++) {
            System.out.printf("  [%d] %s\n", i, data.serviceUuids.get(i));
        }
        System.out.println();
        System.out.println("字节数据 (" + (data.serviceUuids.size() * 2) + "字节):");
        byte[] bytes = serviceUuidsToBytes(data.serviceUuids);
        for (int i = 0; i < bytes.length; i++) {
            System.out.printf("%02X ", bytes[i]);
            if ((i + 1) % 8 == 0) System.out.println();
        }
        System.out.println();
    }
}
